var mongoose = require('mongoose');
var log4js = require('log4js');
var logger = log4js.getLogger();

module.exports.open = function(config) {
    var db = mongoose.connection;
    var host = config.host;
    var port = config.port;
    var database = config.database;
    var options = config.options;
    db.open(host, database, port, options);
    db.on('error', function (err) {
        logger.error("connect error :" + err);
        db.close();
    });
    //监听db close event并重新连接
    db.on('close', function () {
        logger.info("connect closed ");
    });

    db.on('connection',function(){
        logger.info('connection');
    });

    db.on('connected',function(){
        logger.info('connected');
    });

    db.on('open',function(){
        logger.info('open');
    });

    db.on('disconnecting',function(){
        logger.info('disconnecting');
    });

    db.on('disconnected',function(){
        logger.info('disconnected');
    });

    db.on('reconnected',function(err,data){
        logger.info('reconnected');
    });

    return db;
}